package mess;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LeeCode_39 {
    public static void main(String[] args) {
        int[] arr = new int[]{2,3,6,7};
        System.out.println(combinationSum(arr, 7));
    }

    private static List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        backTrick(candidates, result, list, target, 0, 0);
        return result;
    }

    private static void backTrick(int[] candidates, List<List<Integer>> result, List<Integer> list, int target, int index, int sum){
        if (sum > target)
            return;
        else if (sum == target){
            result.add(new ArrayList<>(list));
            return;
        }

        int len = candidates.length;
        for (int i = index; i < len; i++) {
            list.add(candidates[i]);
            sum += candidates[i];
            backTrick(candidates, result, list, target, i, sum);
            sum -=  list.get(list.size() - 1);
            list.remove(list.size() - 1);
        }
    }
}
